<template>
    <div>
        <div
            id='mse'

            :style="customStyle"
            v-if="type === 'VOD'"
        ></div>
        <div v-else>
            <div class="controls" v-if="!playBtnShow">
                <button @click="playAudio"><van-icon :name="iconName"/></button>
                <span>{{audTime}} / {{audAllTime}}</span>
                <van-dropdown-menu direction="up" :overlay="false" v-if="!is_android_ios().android">
                    <van-dropdown-item v-model="value1" :options="option1" @change="changeAudioPlayRate"/>
                </van-dropdown-menu>
            </div>
            <audio :src="videoConfig.videoUrl" ref="aud"></audio>
        </div>
        <!-- <div class="playBtn" @click="playAudio" v-if="playBtnShow">
            <van-icon name="play"/>
        </div> -->
    </div>
</template>

<script>
// import Player from 'xgplayer';
import Player from 'xgplayer';
import HlsJsPlayer from 'xgplayer-hls.js';
import { Toast, Dialog } from 'vant';
//
export default {
    name: 'xgplayerHls',
    data: function() {
        return {
            player: null,
            turnObj: {
                height: '100vh !important',
                minWidth: '100%',
                width: '100% !important',
                left: '0%',
                transform: 'rotate(0deg)'
            },
            config: {
                id: 'mse',
                url: '',
                fluid: true,
                playbackRate: [0.75, 1, 1.5, 2],
                defaultPlaybackRate: 1,
                definitionActive: 'click',
                poster: '',
                volume: 1,
                autoplay: false, // 手动点击播放，节省用户流量
                playsinline: true,
                lastPlayTime: 0, //视频起播时间（单位：秒）
                lastPlayTimeHideDelay: 3,
                enableVideoDbltouch: true,
                rotateFullscreen: true,
                // rotate: {
                //     innerRotate: true,
                //     clockwise: false
                // },
                fitVideoSize: 'auto'
            },
            inFullscreen: false,
            inLandscape: false,
            iconName: 'play',
            audTime: '',
            audAllTime: '',
            option1: [
                { text: '2x', value: 2 },
                { text: '1.5x', value: 1.5 },
                { text: '1x', value: 1 },
                { text: '0.75x', value: 0.75 }
            ],
            value1: 1,
            playBtnShow: false
        };
    },
    components: {
        vanToast: Toast,
        [Dialog.Component.name]: Dialog.Component
    },
    computed: {
        // h5通过监听屏幕角度去写入样式
        customStyle() {
            const that = this;
            if (that.inFullscreen && that.inLandscape) {
                return {
                    height: '100vh !important',
                    minWidth: '100%',
                    width: '100% !important',
                    left: '0%',
                    transform: 'rotate(0deg)'
                };
            } else if (that.inLandscape) {
                return {
                    width: '100% !important',
                    height: '200px !important'
                };
            } else {
                return {
                    width: '100%',
                    height: '200px'
                };
            }
        }
    },
    props: {
        rootStyle: {
            type: Object,
            default() {
                return {};
            }
        },
        iosTimes: {
            type: Boolean,
            default() {
                return false;
            }
        },
        videoConfig: {
            type: Object,
            default() {
                return {videoUrl: '', lastPlayTime: 0};
            }
        },
        modOpenTrial: {
            type: Boolean,
            default() {
                return false;
            }
        },
        modDrag: {
            type: Boolean,
            default() {
                return true;
            }
        },
        fastForward: {
            type: Boolean,
            default() {
                return true;
            }
        },
        type: {
            type: String,
            default() {
                return 'VOD';
            }
        }
    },
    methods: {
        playAudio() {
            if (this.playBtnShow) {
                this.player.currentTime = this.videoConfig.lastPlayTime;
            }
            this.playBtnShow = false;
            this.iconName = this.iconName === 'play' ? 'pause' : 'play';
            this.player.paused ? this.player.play() : this.player.pause();
        },
        changeAudioPlayRate() {
            this.player.playbackRate = this.value1;
        },
        // 秒数转换分+秒
        s_to_MS(s) {
            let m;
            m = Math.floor(s / 60);
            s = Math.floor(s % 60);
            m += '';
            s += '';
            s = s.length === 1 ? '0' + s : s;
            m = m.length === 1 ? '0' + m : m;
            if (isNaN(m)) {
                return '&infin;';
            }
            return m + ':' + s;
        },
        handleOrientation() {
            console.log(this.player);
            const orientation = window.orientation;
            switch (orientation) {
            case 0:
                // 竖屏
                this.inLandscape = false;
                break;
            case 90:
                // 左横屏
                this.inLandscape = true;
                break;
            case -90:
                // 右横屏
                this.inLandscape = true;
                break;
            case 180:
                // 倒立
                break;
            default:
                // 未知
                break;
            }
        },
        init() {
            if (this.videoConfig.videoUrl) {
                let that = this;
                if (this.type === 'VOD') {
                    this.config.lastPlayTime = this.videoConfig.lastPlayTime;
                    this.config.url = this.videoConfig.videoUrl;
                    this.config.ignores = this.fastForward ? [] : ['progress'];
                    if (this.videoConfig.duration) {
                        this.config.duration = this.videoConfig.duration;
                    }
                    // m3u8 格式播放
                    if (this.videoConfig.videoUrl.indexOf('m3u8') !== -1) {
                        this.config.preloadTime = 15; // 预加载时间15s
                        this.config.minCachedTime = 5; // 最小缓存时间
                        // iOS手机不兼容此项属性，故作此判断
                        if (this.is_android_ios().android) {
                            this.config.useHls = true;
                        }
                        this.player = new HlsJsPlayer(this.config);
                        //this.player.start(this.videoConfig.videoUrl);
                    } else {
                        this.player = new Player(this.config);
                        if (this.iosTimes) {
                            if (this.player) {
                                this.player.start(this.videoConfig.videoUrl);
                                this.player.play();
                            }
                        }
                    }
                    // 进入全屏
                    this.player.on('getRotateFullscreen', function(value) {
                        console.log(value, '==this.config=', this.config);
                        if (document.getElementsByClassName('water-turn')[0]) {
                            document.getElementsByClassName('water-turn')[0].style.transform = 'rotate(90deg)';
                        }
                        that.inFullscreen = true;
                        that.$emit('on-goLandscape', 'ON');
                    });
                    // 退出全屏
                    this.player.on('exitRotateFullscreen', function(value) {
                        // console.log(value);
                        if (document.getElementsByClassName('water-turn')[0]) {
                            document.getElementsByClassName('water-turn')[0].style.transform = 'rotate(0deg)';
                        }
                        that.inFullscreen = false;
                        that.$emit('on-goLandscape', 'OFF');
                    });
                } else if (this.type === 'AUD') {
                    this.player = this.$refs.aud;
                    this.player.on = function(method, func) {
                        that.player.addEventListener(method, func);
                    };
                    this.player.addEventListener('canplay', function() {
                        that.audTime = that.s_to_MS(that.videoConfig.lastPlayTime);
                        that.audAllTime = that.s_to_MS(that.player.duration);
                    });
                }
                this.player.on('timeupdate', function(player) {
                    // 是否有权限观看完整视频， true: 能 ， false： 禁止拖拽； 限制 10%；
                    if (!that.modOpenTrial && (player.currentTime / player.duration) >= 0.1) {
                        that.player.pause();
                        that.player.currentTime = 0;
                        Dialog.alert({
                            width: '80%',
                            confirmButtonColor: '#00aeef',
                            confirmButtonText: that.$t('mall_10'),
                            message: this.$t('see_end')
                        });
                    }
                    if (that.type === 'AUD') {
                        that.audTime = that.s_to_MS(that.player.currentTime);
                    }
                    //事件名称可以在上述查询
                    that.$emit('playerVideo', that.player);
                });
            }
        },
        // 判断是在安卓还是ios打开
        is_android_ios() {
            let u = navigator.userAgent;
            return {
                //移动终端浏览器版本信息
                trident: u.indexOf('Trident') > -1, //IE内核
                presto: u.indexOf('Presto') > -1, //opera内核
                webKit: u.indexOf('AppleWebKit') > -1, //苹果、谷歌内核
                gecko: u.indexOf('Gecko') > -1 && u.indexOf('KHTML') === -1, //火狐内核
                mobile:
                    !!u.match(/AppleWebKit.*Mobile/i) ||
                    !!u.match(
                        /MIDP|SymbianOS|NOKIA|SAMSUNG|LG|NEC|TCL|Alcatel|BIRD|DBTEL|Dopod|PHILIPS|HAIER|LENOVO|MOT-|Nokia|SonyEricsson|SIE-|Amoi|ZTE/
                    ), //是否为移动终端
                ios: !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/), //ios终端
                android: u.indexOf('Android') > -1 || u.indexOf('Linux') > -1, //android终端或者uc浏览器
                iPhone: u.indexOf('iPhone') > -1 || u.indexOf('Mac') > -1, //是否为iPhone或者QQHD浏览器
                iPad: u.indexOf('iPad') > -1, //是否iPad
                webApp: u.indexOf('Safari') === -1 //是否web应该程序，没有头部与底部
            };
        }
    },
    mounted() {
        // 是否有权限观看完整视频， true: 能 ， false： 禁止拖拽； 限制 10%；
        this.config.disableProgress = !this.modOpenTrial;
        //如果禁止拖动，后台设置的false,前端设置值得是true.如果允许拖动，后台设置的true,前端设置值得是false.
        this.config.allowSeekPlayed = !this.modDrag;
        this.init();
        window.addEventListener('orientationchange', this.handleOrientation);
    },
    watch: {
        modOpenTrial(val) {
            // 是否有权限观看完整视频， true: 能 ， false： 禁止拖拽； 限制 10%；
            this.config.disableProgress = !this.val;
        },
        videoConfig(val) {

        }
    },
    beforeDestroy() {
        if (this.type === 'VOD') {
            this.player && typeof this.player.destroy === 'function' && this.player.destroy();
        }
    }
};
</script>
<style lang="less" scoped>
/deep/ .van-dropdown-menu__title::after {
    opacity: 0;
}
/deep/ .van-dropdown-menu__bar {
    height: auto;
    background: transparent;
    box-shadow: none;
}
.controls {
    position: absolute;
    bottom: 0;
    left: 0;
    width: 85%;
    display: flex;
    padding-left: 10px;
    justify-content: space-between;
    background: transparent;
    color: #fff;
    &>span {
        flex: 1;
        line-height: 34px;
        padding-left: 20px;
    }
    &>button {
        background: transparent;
        border: 0;
    }
}
/deep/ .van-dropdown-menu__title {
    color: #fff;
}
/deep/ .van-icon {
    background: transparent;
}
/deep/ .van-icon:before {
    color: #fff;
    font-size: 30px;
}
/deep/ .van-ellipsis {
    line-height: 34px;
}
/deep/ .van-dropdown-item {
    position: absolute;
    top: -100px;
    height: 100px;
    width: 80px ;
    left: 50%;
    transform: translateX(-50%);
}
/deep/ .van-dropdown-menu {
    position: relative;
}
/deep/ .van-dropdown-item__content {
    max-height: 100%;
}
/deep/ .van-cell {
    line-height: 25px;
    padding: 0;
    color: #fff;
    background: transparent;
}
/deep/ .van-cell::after {
    border: 0;
}
/deep/ .van-dropdown-item__option {
    text-align: center;
}
/deep/.van-popup {
    background: transparent;
}
/deep/ .van-cell__value {
    display: none;
}
.playBtn {
    position: absolute;
    left: 50%;
    top: 50%;
    transform: translate(-50%, -50%);
    /deep/ .van-icon:before {
        color: #fff;
        font-size: 40px;
    }
}
#mse{
    padding-top: 0!important;
    min-height: 200px!important;
}
</style>
